
#include "TcpClient.h"

TcpClient::TcpClient(QObject *parent) :
	QObject(parent)
{
	mTimer = new QTimer(this);
    mTimer->setSingleShot(true);
    connect(mTimer, SIGNAL(timeout()), this, SLOT(On_TimeOut()));

	mTcpSocket = new QTcpSocket(this);

	connect(mTcpSocket, SIGNAL(connected()), this, SLOT(tcp_connected()));
    connect(mTcpSocket, SIGNAL(disconnected()), this, SLOT(tcp_disconnected()));
    connect(mTcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(processError(QAbstractSocket::SocketError)));
    connect(mTcpSocket, SIGNAL(readyRead()), this, SLOT(processReadyRead()));
}

TcpClient::~TcpClient()
{

}

void TcpClient::OnStart(void)
{
	connect_to_Server();
}

void TcpClient::tcp_connected(void)
{
	qDebug() << __func__;
}

void TcpClient::tcp_disconnected(void)
{
	qDebug() << __func__;
	trigger_timer();
}

void TcpClient::processError(QAbstractSocket::SocketError socketError)
{
	qDebug() << __func__;

	Q_UNUSED(socketError);
    QTcpSocket *tcpSocket = static_cast<QTcpSocket *>(sender());
    tcpSocket->abort();

    trigger_timer();
}

void TcpClient::processReadyRead(void)
{
	QTcpSocket *tcpSocket = static_cast<QTcpSocket *>(sender());
    QByteArray data = tcpSocket->readAll();

	emit socket_receive(data);
}

void TcpClient::On_TimeOut(void)
{
    connect_to_Server();
}

void TcpClient::connect_to_Server(void)
{
	QHostAddress lisAddr("192.168.0.105");
    quint16 lisPort = 4001;

    mTcpSocket->connectToHost(lisAddr, lisPort);
}

void TcpClient::trigger_timer(void)
{
	mTimer->start(5000);
}

